﻿using System;
using System.Runtime.Serialization;

namespace Framework.Unity
{
    public sealed class ImplementationRetrievalException : Exception
    {
        private const string ContractToFulfilFieldName = "ImplementationRetrievalException._contractToFulfil";

        private readonly Type _contractToFulfil;

        public ImplementationRetrievalException(Type contract, Exception e)
            : base(GetMessage(contract), e)
        {
            _contractToFulfil = contract;
        }

        public ImplementationRetrievalException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _contractToFulfil = (Type)info.GetValue(ContractToFulfilFieldName, typeof(Type));
        }

        public Type ContractToFulfil
        {
            get { return _contractToFulfil; }
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue(ContractToFulfilFieldName, _contractToFulfil);
        }

        private static string GetMessage(Type contract)
        {
            return string.Format(
                "Failed to retrieve an implementation of contract: {0}.",
                contract.Name);
        }
    }
}